package com.slz3.business.module.configManagement.conIndexNewGoods.steward;

import com.slz3.business.frame.steward.FindJoinSteward;
import com.slz3.business.frame.util.VE;
import com.slz3.business.module.configManagement.conIndexNewGoods.domain.ConIndexNewGoods;
import com.slz3.business.module.configManagement.conIndexNewGoods.domain.ConIndexNewGoodsCondition;
import com.slz3.business.module.configManagement.conIndexNewGoods.domain.ConIndexNewGoodsFactory;
import com.slz3.business.module.templateExample.temStyle1.domain.TemStyle1Condition;
import com.slz3.business.module.templateExample.temStyle1.domain.TemStyle1Factory;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.MultiValueMap;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

public class ConIndexNewGoodsSpecification {

    public static FindJoin findJoin(MultiValueMap<String, String> params) {
        return new FindJoin(params);
    }

    private static class FindJoin implements Specification<ConIndexNewGoods> {

        private MultiValueMap<String, String> params;

        private ConIndexNewGoodsCondition condition;

        public FindJoin(MultiValueMap<String, String> params) {
            this.params = params;
            this.condition = ConIndexNewGoodsFactory.newConIndexNewGoodsCondition(params);
        }

        @Override
        public Predicate toPredicate(Root<ConIndexNewGoods> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            final List<Predicate> predicateList = new ArrayList<>();

            predicateList.addAll(FindJoinSteward.appoint(root, cb, ConIndexNewGoods.class, params));

            if (VE.isNotEmpty(condition.getCreateTimeOUTSET()))
                predicateList.add(cb.greaterThanOrEqualTo(root.get("createTime"), condition.getCreateTimeOUTSET()));

            if (VE.isNotEmpty(condition.getCreateTimeFINISH()))
                predicateList.add(cb.lessThanOrEqualTo(root.get("createTime"), condition.getCreateTimeFINISH()));

            if (VE.isNotEmpty(condition.getLastModifyTimeOUTSET()))
                predicateList.add(cb.greaterThanOrEqualTo(root.get("lastModifyTime"), condition.getLastModifyTimeOUTSET()));

            if (VE.isNotEmpty(condition.getLastModifyTimeFINISH()))
                predicateList.add(cb.lessThanOrEqualTo(root.get("lastModifyTime"), condition.getLastModifyTimeFINISH()));

            if (VE.isNotEmpty(condition.getSerAuditList())) {
                CriteriaBuilder.In in = cb.in(root.get("serAudit"));
                condition.getSerAuditList().forEach(item -> in.value(item));
                predicateList.add(in);
            }

            return predicateList.size() > 0 ? cb.and(predicateList.toArray(new Predicate[]{})) : null;

        }

    }

}
